package com.yifan.utils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

public class SessionFilter implements Filter {

	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        res.addHeader("Access-Control-Allow-Origin", "*");
        String uri = req.getRequestURI();
        System.out.println(uri);
        // System.out.println(uri.indexOf("addUser"));
        if (uri.indexOf("login") != -1 || uri.indexOf("Login") != -1  || uri.indexOf("user") != -1 ) {
            chain.doFilter(req, res);
        } else if (uri.contains(".css") || uri.contains(".js") || uri.contains(".jpg") || uri.contains(".png") || uri.contains(".gif")
                || uri.contains(".jpng") || uri.contains(".html") || uri.contains(".html") || uri.contains(".json") || uri.contains(".woff")
                || uri.contains(".woff2") || uri.contains(".ttf")  || uri.contains(".jpeg")
                  || uri.contains(".swf") && !uri.contains(".jsp") || uri.contains("registration")) {
            chain.doFilter(req, res);
        } else {
            HttpSession session = req.getSession();
            Object userid = session.getAttribute("userid");
            if (userid != "" && userid != null ) {
                chain.doFilter(req, res);
            } else {
                //System.out.println(uri.indexOf("registration") );
                session.invalidate();
                res.setContentType("text/html;charset=utf-8");
                PrintWriter out = res.getWriter();
                out.println("<script language='javascript' type='text/javascript'>");
                out.println("window.top.location.href='" + req.getContextPath() + "/login.jsp'");
                out.println("</script>");
            }
        }
    }

	public void destroy() {

	}

}
